package com.ssaurel.mysleepquality.sleeptracker

import android.app.Application
import android.content.res.Resources
import androidx.lifecycle.*
import com.ssaurel.mysleepquality.database.SleepDatabaseDao
import com.ssaurel.mysleepquality.database.SleepNight
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.lang.IllegalArgumentException

/**
 * @ProjectName : MySleepQuality
 * @Author : 作者
 * @Time : 2021/10/11 10:38
 * @Description : 文件描述
 */
class SleepTrackerViewModel(val database:SleepDatabaseDao,
                            application : Application) : AndroidViewModel(application){

    private var tonight = MutableLiveData<SleepNight>()
    private val nights = database.getAllNights()
    val nightString = Transformations.map(nights){ nights ->
        formatNights(nights,application.resources)
    }

    private fun formatNights(nights: List<SleepNight>?, resources: Resources?) {

    }

    init {
        initializeTonight()
    }

    private fun initializeTonight() {
        viewModelScope.launch {
            tonight.value = getTonightFromDatabase()
        }
    }

    private suspend fun getTonightFromDatabase(): SleepNight? {
        var night = database.getTonight()
        if (night?.endTimeMilli != night?.startTimeMilli){
            night = null
        }
        return night
    }

    fun onStartTracking(){
        viewModelScope.launch {
            val newNight = SleepNight()
            insert(newNight)
            //更新night
            tonight.value = getTonightFromDatabase()
        }

    }

    private suspend fun insert(newNight: SleepNight) {
        database.insert(newNight)
    }

//    //无房
//    fun someWorkNeedsToBeDon(){
//        viewModelScope.launch {
//            suspendFunction()
//        }
//    }
//
//    private suspend fun suspendFunction() {
//        withContext(Dispatchers.IO){
//            longrunningWork()
//        }
//    }
}